import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { stationList, addStation, updateStation, delStation, GetAllStation } from '@/utils/api/dispatch/station'
import { GetAllMap } from '@/utils/api/dispatch/map'

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    const form = reactive({
        stationname: "",
        x: "",
        y: "",
        stationtype: "",
        status: null,
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle, statusStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });
    // 所属地图select
    var mapTypes = ref([])
    // 站点select
    var stationSelect = ref([])
    // 类型select
    const stationTypes = [
        { value: 0, label: $t('station.waypoint') },
        { value: 1, label: $t('station.returnPoint') },
        { value: 2, label: $t('station.chargingPoint') },
        { value: 3, label: $t('station.cargoPoint') },
        { value: 4, label: $t('station.elevatorPoint') },
    ]

    // 类型
    function formatType(status) {
        const stateMap = {
            0: $t('station.waypoint'),
            1: $t('station.returnPoint'),
            2: $t('station.chargingPoint'),
            3: $t('station.cargoPoint'),
            4: $t('station.elevatorPoint')
        }
        return stateMap[status]
    }

    // 状态
    function formatStatus(status) {
        const stateMap = {
            0: $t('station.disable'),
            1: $t('station.enable'),
            2: $t('station.lock'),
        }
        return stateMap[status]
    }

    const columns = ref<TableColumnList>([
        {
            label: $t('station.stationName'),
            prop: "name",
            width: 120,
            align: "left",
            sortable: true
        },
        {
            label: $t('station.xAxis'),
            prop: "x",
            width: 100,
            align: "left",
            sortable: true
        },
        {
            label: $t('station.yAxis'),
            prop: "y",
            width: 100,
            align: "left",
            sortable: true
        },
        {
            label: $t('station.angle'),
            prop: "angle",
            width: 100,
            align: "left",
            sortable: true
        },
        {
            label: $t('station.mapToWhichItBelongs'),
            prop: "mapid",
            minWidth: 140,
            cellRenderer: ({ row, props }) => (
                <span>{mapTypes.value.find(v => { return v.id === row.mapid })?.name}</span >
            )
        },
        {
            label: $t('station.status'),
            prop: "status",
            minWidth: 100,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={statusStyle.value(row.status)}>
                    {formatStatus(row.status)}
                </el-tag>
            )
        },
        {
            label: $t('station.siteType'),
            prop: "type",
            minWidth: 120,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.type)}>
                    {formatType(row.type)}
                </el-tag>
            )
        },
        {
            label: $t('station.associatedGeneralMapSites'),
            prop: "parentid",
            minWidth: 150,
            cellRenderer: ({ row, props }) => (
                <span>{stationSelect.value.find(v => { return v.stationid === row.parentid })?.stationname}</span >
            )
        },
        {
            label: $t('station.remarks'),
            prop: "note",
            minWidth: 200,
            align: "left"
        },
        {
            label: $t('station.operation'),
            headerAlign: "center",
            fixed: "right",
            align: "right",
            width: locale.value === "zh" ? 200 : 250,
            slot: "operation"
        }
    ])

    function tableReloading() {
        columns.value = [
            {
                label: $t('station.stationName'),
                prop: "name",
                width: 120,
                align: "left",
                sortable: true
            },
            {
                label: $t('station.xAxis'),
                prop: "x",
                width: 100,
                align: "left",
                sortable: true
            },
            {
                label: $t('station.yAxis'),
                prop: "y",
                width: 100,
                align: "left",
                sortable: true
            },
            {
                label: $t('station.angle'),
                prop: "angle",
                width: 100,
                align: "left",
                sortable: true
            },
            {
                label: $t('station.mapToWhichItBelongs'),
                prop: "mapid",
                minWidth: 140,
                cellRenderer: ({ row, props }) => (
                    <span>{mapTypes.value.find(v => { return v.id === row.mapid })?.name}</span >
                )
            },
            {
                label: $t('station.status'),
                prop: "status",
                minWidth: 100,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={statusStyle.value(row.status)}>
                        {formatStatus(row.status)}
                    </el-tag>
                )
            },
            {
                label: $t('station.siteType'),
                prop: "type",
                minWidth: 120,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.type)}>
                        {formatType(row.type)}
                    </el-tag>
                )
            },
            {
                label: $t('station.associatedGeneralMapSites'),
                prop: "parentid",
                minWidth: 150,
                cellRenderer: ({ row, props }) => (
                    <span>{stationSelect.value.find(v => { return v.stationid === row.parentid })?.stationname}</span >
                )
            },
            {
                label: $t('station.remarks'),
                prop: "note",
                minWidth: 200,
                align: "left"
            },
            {
                label: $t('station.operation'),
                headerAlign: "center",
                fixed: "right",
                align: "right",
                width: locale.value === "zh" ? 200 : 250,
                slot: "operation"
            }
        ]
    }

    async function onSearch() {
        loading.value = true;
        //@ts-ignore
        const { Content } = await stationList(form);
        let newData = Content.Results;
        dataList.value = newData;
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        const newTitle = title === "新增" ? $t('station.addNewSite') : $t('station.editSite');
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    name: row?.name ?? "",
                    type: row?.type ?? null,
                    x: row?.x ?? null,
                    y: row?.y ?? null,
                    sort: row?.sort ?? null,
                    status: row?.status ?? 1,
                    laser: row?.laser ?? 0,
                    qrcode: row?.qrcode ?? 0,
                    note: row?.note ?? "",
                    mapid: row?.mapid ?? null,
                    parentid: row?.parentid ?? undefined,
                },
                mapTypes: mapTypes || [],
                stationSelect: stationSelect || []
            },
            width: "35%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(elForm, { ref: formRef } as any),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message(`您${title}了站点名称为${curData.name}的这条数据`, {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        // console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            addStation(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { id: row.id })
                            updateStation(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            `是否确认删除站点名称为${row.name}的数据项?`,
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delStation(row.id).then(res => {
                if (res.Code === 0) {
                    message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        // 地图select
        let { Content: map } = await GetAllMap()
        let allMap = map.filter(v => { return v.type === 0 })
        mapTypes.value = map
        // 站点select
        let { Content: stations } = await GetAllStation({ status: 1, mapid: allMap[0].id })
        stationSelect.value = stations
        onSearch()
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        stationTypes,
        tableReloading
    }
}